package net.babelphish.altitudesig;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public abstract class DataScraper {

	protected Integer _rating;
	protected Integer _rank;	
	protected String _playerName;
	protected String _winLoss;
	protected ArrayList<Double> _ratings;
	protected String _dataLocation;
	
	public DataScraper(String dataLocation) {
		_dataLocation = dataLocation;
	}
	
	protected URL generateURL(String vaporID) throws MalformedURLException {
		return new URL(_dataLocation + "id=" + vaporID);
	}
	
	//returns false if scraping was unsuccessful;
	boolean scrapeData(String vaporID, GAME_TYPE gameType) {
		try {
			URLFetchService fetchService = URLFetchServiceFactory.getURLFetchService();
			HTTPResponse contentLookup = fetchService.fetch(generateURL(vaporID));
			StringBuilder scrapedContent = new StringBuilder(new String(contentLookup.getContent()));
		
			return processScrapedData(scrapedContent, gameType);
		}
		catch(Exception e) {
			return false;
		}
	}
	
	abstract boolean processScrapedData(StringBuilder scrapedData, GAME_TYPE gameType);
		
	public Integer getCurrentRating() { 
		return _rating;
	}

	public String getName() {
		return _playerName;
	}
	
	public Integer getRank() {
		return _rank;
	}

	public ArrayList<Double> getRatings() {
		return _ratings; 
	}

	public String getWinLoss() {
		return _winLoss;
	}
	
	public String getBadge() {		
		if (_rank == 1) {
			return "1";
		} else { // 	
			for (Integer i = 2000; i >= 1200; i-= 100)
			{
				if (_rating >= i) {
					return i.toString();
				}
			}
			return "1100";
		}
	}
	
}
